package org.dromara.basic.controller;

import java.io.File;
import java.io.FilenameFilter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.dev33.satoken.annotation.SaIgnore;
import cn.hutool.core.io.file.FileNameUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.constraints.*;
import cn.dev33.satoken.annotation.SaCheckPermission;
import org.apache.poi.ss.formula.functions.T;
import org.dromara.basic.domain.FaceImage;
import org.dromara.basic.domain.bo.MemberBo;
import org.dromara.basic.domain.vo.MemberVo;
import org.dromara.basic.domain.vo.TeachClassVo;
import org.dromara.basic.service.IMemberService;
import org.dromara.common.core.domain.model.LoginUser;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.utils.FileUploadUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.validation.annotation.Validated;
import org.dromara.common.idempotent.annotation.RepeatSubmit;
import org.dromara.common.log.annotation.Log;
import org.dromara.common.web.core.BaseController;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.core.domain.R;
import org.dromara.common.core.validate.AddGroup;
import org.dromara.common.core.validate.EditGroup;
import org.dromara.common.log.enums.BusinessType;
import org.dromara.common.excel.utils.ExcelUtil;
import org.dromara.basic.domain.vo.FaceImageVo;
import org.dromara.basic.domain.bo.FaceImageBo;
import org.dromara.basic.service.IFaceImageService;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

/**
 * 学生人脸信息
 *
 * @author chl
 * @date 2024-10-17
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/pe/faceImage")
public class FaceImageController extends BaseController {

    private final IFaceImageService faceImageService;
    private final IMemberService memberService;

    /**
     * 查询学生人脸信息列表
     */
    @SaCheckPermission("pe:faceImage:list")
    @GetMapping("/list")
    public TableDataInfo<FaceImageVo> list(FaceImageBo bo, PageQuery pageQuery) {
        return faceImageService.queryPageList(bo, pageQuery);
    }

    /**
     * 导出学生人脸信息列表
     */
//    @SaCheckPermission("pe:faceImage:export")
    @SaIgnore
    @Log(title = "学生人脸信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(FaceImageBo bo, HttpServletResponse response) {
        List<FaceImageVo> list = faceImageService.queryList(bo);
        ExcelUtil.exportExcel(list, "学生人脸信息", FaceImageVo.class, response);
    }

    /**
     * 获取学生人脸信息详细信息
     *
     * @param id 主键
     */
    @SaCheckPermission("pe:faceImage:query")
    @GetMapping("/{id}")
    public R<FaceImageVo> getInfo(@NotNull(message = "主键不能为空")
                                     @PathVariable Long id) {
        return R.ok(faceImageService.queryById(id));
    }

    /**
     * 新增学生人脸信息
     */
    @SaCheckPermission("pe:faceImage:add")
    @Log(title = "学生人脸信息", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping()
    public R<Void> add(@Validated(AddGroup.class) @RequestBody FaceImageBo bo) {
        return toAjax(faceImageService.insertByBo(bo));
    }

    /**
     * 修改学生人脸信息
     */
    @SaCheckPermission("pe:faceImage:edit")
    @Log(title = "学生人脸信息", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping()
    public R<Void> edit(@Validated(EditGroup.class) @RequestBody FaceImageBo bo) {
        return toAjax(faceImageService.updateByBo(bo));
    }

    /**
     * 删除学生人脸信息
     *
     * @param ids 主键串
     */
    @SaCheckPermission("pe:faceImage:remove")
    @Log(title = "删除学生人脸信息", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")
                          @PathVariable Long[] ids) {
        return toAjax(faceImageService.deleteWithValidByIds(List.of(ids), true));
    }
    /**
     * 批量导入学生底图并且关联学生信息
     */
    @SaIgnore
    @RequestMapping("/upload")
    @ResponseBody
    public R<T> upload(HttpServletRequest request) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        List<MultipartFile> files = multipartRequest.getFiles("file");
        if(CollectionUtils.isEmpty(files)){
            return R.fail("图片导入失败,上传文件为空");
        }
        faceImageService.synchronizeImage(files);
        return R.ok("成功");
    }
    /**
     * 批量导入学生底图并且关联学生信息
     */
    @SaIgnore
    @RequestMapping("/upload/one")
    @ResponseBody
    public R<T> uploadOne(@RequestParam("file") MultipartFile file,@RequestParam("faceImageB") String faceImage) {
        JSONObject jsonObject = JSONObject.parseObject(faceImage);
        String stuNum = jsonObject.getString("stuNum");
        Long id = jsonObject.getLong("id");
        FaceImageBo bo =new FaceImageBo();
        if(StringUtils.isNotEmpty(stuNum)){
            bo.setStuNum(stuNum);
        }else {
            return R.fail("学号不能为空");
        }
        if(id!=null){
            bo.setId(id);
        }
        faceImageService.synchronizeImage(file,bo);
        return R.ok("成功");
    }
    /**
     * 批量关联学生信息
     */
    @SaCheckPermission("pe:faceImage:batchCreate")
    @Log(title = "批量关联学生信息", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping("/batchCreate")
    public R<Void> batchCreate(MemberBo bo) {
        return toAjax(faceImageService.batchCreate(bo));
    }

    /**
     * 批量同步多设备多学生底图
     */
    @SaCheckPermission("pe:faceImage:device:batch")
    @Log(title = "批量同步多设备多学生底图", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping("/synchronize/device/batch")
    public R<Void> synchronizeDeviceBatch(@RequestBody FaceImageBo bo) {
        return toAjax(faceImageService.synchronizeDeviceBatch(bo));
    }

    /**
     * 同步一名学生设备底图
     */
//    @SaCheckPermission("pe:faceImage:device:one")
    @SaIgnore
    @Log(title = "同步一名学生设备底图", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping("/synchronize/device/one")
    public R<Void> synchronizeDeviceOne(@RequestBody FaceImageBo bo) {
        return toAjax(faceImageService.synchronizeDeviceOne(bo));
    }

    /**
     * 批量删除设备底图
     */
    @SaCheckPermission("pe:faceImage:device:remove")
    @Log(title = "批量删除设备底图", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping("/synchronize/device/remove")
    public R<Void> synchronizeDeviceBatchRemove(@RequestBody FaceImageBo bo) {
        return toAjax(faceImageService.synchronizeDeviceBatchRemove(bo));
    }

    @SaIgnore
    @PostMapping("/add/image/url")
    public R<Void> addImageUrl(@RequestBody FaceImageBo bo) {
        List<FaceImageVo> faceImageVos = faceImageService.queryList(bo);
        // 创建File对象
        File file = new File(bo.getUrl());
        Map<String,String> urlMapList=new HashMap<>();
        if (file.exists()) { // 判断File对象对应的目录是否存在
            for (File listFile : file.listFiles()) {
                String s = listFile.getName().split("\\.")[0];
                urlMapList.put(s,listFile.getAbsolutePath());
            }
        }
        if(CollectionUtils.isNotEmpty(faceImageVos)){
            for (FaceImageVo faceImageVo : faceImageVos) {
                FaceImageBo faceImageBo = new FaceImageBo();
                faceImageBo.setId(faceImageVo.getId());
                String url=urlMapList.get(faceImageVo.getStuNum());
                if (StringUtils.isNotEmpty(url)) {
                    faceImageBo.setImageUrl(url);
                    Boolean b = faceImageService.updateByBo(faceImageBo);
                    if (!b) {
                        return R.fail("添加失败");
                    }
                }
            }
        }


        return R.ok("添加成功");
    }
}
